package com.zhiwang.xiaoqu.widget.webview

import android.content.Context
import android.graphics.Bitmap
import android.os.Build
import android.util.AttributeSet
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.webkit.*
import android.widget.FrameLayout
import com.zhiwang.xiaoqu.R

class MasterWebView(context: Context, attrs: AttributeSet?) : FrameLayout(context, attrs) {

    lateinit var errorView: View
    lateinit var webView: WebViewEx
    var currUrl: String? = null
    var loadingError = false
    private var retryFunc: (() -> Unit)? = null
    var webViewClientCallBack: WebViewClientCallBack? = null

    var retryView: View? = null

    init {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.MasterWebView)
        addWebView()
        if (typedArray.hasValue(R.styleable.MasterWebView_mw_error_view)) {
            errorView = LayoutInflater.from(context)
                .inflate(typedArray.getResourceId(R.styleable.MasterWebView_mw_error_view, 0), null)
            val layoutParams = LayoutParams(WRAP_CONTENT, WRAP_CONTENT)
            layoutParams.gravity = Gravity.CENTER
            errorView.visibility = View.GONE
            errorView.layoutParams = layoutParams
            addView(errorView)
            setUpRetryListener()

            if (typedArray.hasValue(R.styleable.MasterWebView_mw_retry_view_id)) {
                retryView =
                    errorView.findViewById(typedArray.getResourceId(R.styleable.MasterWebView_mw_retry_view_id, 0))
            }
        }

        typedArray.recycle()
    }

    private fun setUpRetryListener() {
        /* errorView.findViewById<TextView>(R.id.reload_btn)*/retryView?.setOnClickListener {
            loadingError = false
            if (retryFunc != null)
                retryFunc!!()
        }
    }

    fun setRetryListener(func: () -> Unit) {
        this.retryFunc = func
    }

    private fun addWebView() {
        try {
            webView = WebViewEx(context)

        } catch (e: Exception) {
            webView = WebViewEx(context.applicationContext)
        }
        webView.layoutParams = LayoutParams(MATCH_PARENT, MATCH_PARENT)
        addView(webView)
        webView.webChromeClient = WebChromeClient()
        webView.webViewClient = InnerWebViewClient()
    }


    val TAG = "MasterWebView"

    inner class InnerWebViewClient : WebViewClient() {

        @Deprecated("")
        override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
            currUrl = url
            return if (webViewClientCallBack != null) webViewClientCallBack!!.shouldOverrideUrlLoading(view, url)
            else super.shouldOverrideUrlLoading(view, url)
        }

        override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                currUrl = request?.url?.toString()
            }
            return if (webViewClientCallBack != null) webViewClientCallBack!!.shouldOverrideUrlLoading(view, request)
            else
                super.shouldOverrideUrlLoading(view, request)

        }

        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            loadingError = false
            if (webViewClientCallBack != null) webViewClientCallBack!!.onPageStarted(view, url, favicon)
        }

        override fun onPageFinished(view: WebView?, url: String?) {
            if (loadingError.not()) hideErrorView()
            if (webViewClientCallBack != null) webViewClientCallBack!!.onPageFinished(view, url)
        }


        @Deprecated("")
        override fun onReceivedError(view: WebView?, errorCode: Int, description: String?, failingUrl: String?) {
            //错误视图加载逻辑
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                return
            }
            loadingError = true
            showErrorView()
            if (webViewClientCallBack != null) webViewClientCallBack!!.onReceivedError(
                view,
                errorCode,
                description,
                failingUrl
            )
            else super.onReceivedError(view, errorCode, description, failingUrl)
        }

        override fun onReceivedError(view: WebView?, request: WebResourceRequest?, error: WebResourceError?) {
            if (error != null) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && request?.isForMainFrame == true) {
                    loadingError = true
                    showErrorView()
                }
            }
            if (webViewClientCallBack != null) webViewClientCallBack!!.onReceivedError(view, request, error)
            else super.onReceivedError(view, request, error)
        }

        fun showErrorView() {
            webView.visibility = View.INVISIBLE
            errorView.visibility = View.VISIBLE
        }


        fun hideErrorView() {
            webView.visibility = View.VISIBLE
            errorView.visibility = View.GONE
        }

        fun isFailed() = loadingError


    }

}